<template>
  <a-card>
    <template #title>
      <div class="header-title">学生详情</div>
    </template>
    
    <a-card class="info-card" :bordered="false">
    <a-row :gutter="16">
        <a-col :span="8">
          <div class="info-item">
            <div class="label">姓名-班级</div>
            <div class="value">{{ studentInfo.userName || '-' }} - {{ getClassNames() }}</div>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="info-item">
            <div class="label">账号剩余时间</div>
            <div class="value">{{ studentInfo.remainingTime || '-' }}</div>
          </div>
        </a-col>
        <a-col :span="8">
          <!-- 预留位置 -->
        </a-col>
      </a-row>
      
      <a-row :gutter="16" style="margin-top: 16px;">
      <a-col :span="8">
        <div class="info-item">
          <div class="label">手机号</div>
            <div class="value">{{ studentInfo.phone || '-' }}</div>
        </div>
      </a-col>
      <a-col :span="8">
        <div class="info-item">
            <div class="label">日常督促人</div>
            <div class="value">{{ studentInfo.guarder || '-' }} ({{ studentInfo.guarderRelation || '-' }})</div>
        </div>
      </a-col>
      <a-col :span="8">
        <div class="info-item">
          <div class="label">学校</div>
            <div class="value">{{ studentInfo.school || '-' }}</div>
        </div>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px;">
      <a-col :span="8">
        <div class="info-item">
            <div class="label">学龄</div>
            <div class="value">{{ studentInfo.grade || '-' }}</div>
        </div>
      </a-col>
      <a-col :span="8">
        <div class="info-item">
            <div class="label">生日/年龄</div>
            <div class="value">{{ formatDate(studentInfo.birthday) }} / {{ calculateAge(studentInfo.birthday) }}岁</div>
        </div>
      </a-col>
      <a-col :span="8">
        <div class="info-item">
          <div class="label">学习方式</div>
            <div class="value">{{ studentInfo.studentTypeDesc || '-' }}</div>
        </div>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px;">
      <a-col :span="8">
        <div class="info-item">
            <div class="label">已学习时长</div>
            <div class="value">{{ studentInfo.studyDuration || '-' }}</div>
        </div>
      </a-col>
      <a-col :span="8">
        <div class="info-item">
          <div class="label">带班老师</div>
            <div class="value">{{ getTeacherNames() }}</div>
        </div>
      </a-col>
      <a-col :span="8">
        <div class="info-item">
            <div class="label">城市区域</div>
            <div class="value">{{ getCityRegion() }}</div>
        </div>
      </a-col>
    </a-row>
    </a-card>
    
    <a-divider />
    
    <a-row :gutter="16">
      <a-col :span="6">
        <a-card class="stat-card">
          <div class="stat-title">总打卡数据</div>
          <div class="stat-number">{{ studentInfo.totalCheckinDays || 0 }}<span class="stat-unit">次</span></div>
          <div class="stat-rate">
            <span class="rate-value" :class="getRateColorClass(studentInfo.totalCheckinRate)">{{ studentInfo.totalCheckinRate || '0%' }}</span> 打卡率
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <div class="stat-title">当季度打卡</div>
          <div class="stat-number">{{ studentInfo.quarterCheckinDays || 0 }}<span class="stat-unit">次</span></div>
          <div class="stat-rate">
            <span class="rate-value" :class="getRateColorClass(studentInfo.quarterCheckinRate)">{{ studentInfo.quarterCheckinRate || '0%' }}</span> 打卡率
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <div class="stat-title">当月打卡</div>
          <div class="stat-number">{{ studentInfo.monthCheckinDays || 0 }}<span class="stat-unit">次</span></div>
          <div class="stat-rate">
            <span class="rate-value" :class="getRateColorClass(studentInfo.monthCheckinRate)">{{ studentInfo.monthCheckinRate || '0%' }}</span> 打卡率
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <div class="stat-title">本周打卡</div>
          <div class="stat-number">{{ studentInfo.weekCheckinDays || 0 }}<span class="stat-unit">次</span></div>
          <div class="stat-rate">
            <span class="rate-value" :class="getRateColorClass(studentInfo.weekCheckinRate)">{{ studentInfo.weekCheckinRate || '0%' }}</span> 打卡率
          </div>
        </a-card>
      </a-col>
    </a-row>
    
    <a-divider />
    
    <div class="section-header">
      <h3>学习计划完成情况表</h3>
      <div class="section-actions">
        <a-button type="primary" size="small" @click="setPlan(studentInfo)">
          配置计划
        </a-button>
      </div>
    </div>
    
    <a-table 
      :dataSource="studyPlanTableData" 
      :columns="studyPlanColumns" 
      :pagination="paginationConfig" 
      size="middle"
      rowKey="id"
      :loading="!dataLoaded"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'progress'">
          <a-progress :percent="record.progress || 0" :format="percent => `${percent}%`" />
        </template>
        <template v-else-if="column.dataIndex === 'publishAt'">
          {{ formatDate(record.publishAt) || '-' }}
        </template>
        <template v-else-if="column.dataIndex === 'completeAt'">
          {{ formatDate(record.completeAt) || '-' }}
        </template>
        <template v-else-if="typeof column.dataIndex === 'string' && column.dataIndex.indexOf('subTask') === 0">
          <a-tag v-if="record[column.dataIndex] && record[column.dataIndex] !== '-'" color="blue">
            {{ record[column.dataIndex] }}
          </a-tag>
          <a-tag v-else color="default" style="background-color: #f0f0f0; color: #999;">
            -
          </a-tag>
        </template>
      </template>
      <template #emptyText>
        <div style="padding: 16px; text-align: center;">
          <p>{{ dataLoaded ? '暂无学习计划数据' : '正在加载数据...' }}</p>
          <a-button v-if="dataLoaded" type="link" @click="fetchStudyPlans">重新加载</a-button>
        </div>
      </template>
    </a-table>
    
    <!-- 添加计划配置弹窗 -->
    <plan-config-modal
      v-model:visible="planConfigVisible"
      :classData="currentClassData"
      @confirm="handlePlanConfirm"
    />
  </a-card>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Api } from '@/api/';
import { request, baseApiUrl } from '@/utils/request';
import { useUserStore } from '@/store/modules/user';
import { message } from 'ant-design-vue';
import PlanConfigModal from '../class/PlanConfigModal.vue'; // 导入计划配置弹窗组件

interface ClassInfo {
  classId: string;
  className: string;
  classGrade: number;
  teacherName: string;
  teacherId: number;
  startAt: string;
  expireAt: string;
  status: number;
  studyPlan: string[];
  checkinDays: number;
  lastCheckinAt: string | null;
  joinAt: string;
  checkinRate: string;
  mainPlans?: {
    planId: string | number;
    planName: string;
    progress: number;
    publishAt: string;
    completeAt?: string;
    effectivePunchEndAt?: string;
    subPlans?: {
      subPlanId: string | number;
      subPlanName: string;
    }[];
  }[];
}

interface StudentInfo {
  id: string;
  student_id: string;      // 使用下划线命名匹配后端
  phone: string;
  user_name: string;       // 使用下划线命名匹配后端
  user_id: string;
  student_type: number;
  join_at: string | null;
  start_at: string;
  expire_at: string;
  status: number;
  created_at: string;
  updated_at: string;
  is_delete: number;
  create_by: number;
  update_by: number;
  userId: string;
  userRealName: string;
  userPhone: string;
  guarder: string;
  guarderPhone: string;
  guarderRelation: number | string;
  birthday: string;
  grade: number | string;
  school: string;
  classes: ClassInfo[];
  totalCheckinDays: number;
  totalCheckinRate: string;
  province?: string;       // 省份
  city?: string;           // 城市
  userName: string;
  remainingTime: string;
  studentTypeDesc: string;
  studyDuration: string;   // 学习时长
  quarterCheckinDays?: number; // 季度打卡次数
  quarterCheckinRate?: string; // 季度打卡率
  monthCheckinDays?: number;   // 月度打卡次数
  monthCheckinRate?: string;   // 月度打卡率
  weekCheckinDays?: number;    // 周打卡次数
  weekCheckinRate?: string;    // 周打卡率
}

interface SubPlan {
  id: number;
  planId: number;
  subPlanId: string;
  subPlanName: string;
  subPlanMark: string;
  createBy: number;
  updateBy: number;
  createdAt: string;
  updatedAt: string;
  isDelete: number;
}

interface MainPlan {
  id: number;
  planId: string;
  planName: string;
  classId: string;
  mark: string;
  progress: number;
  punchStartAt: string;
  publishAt: string;
  completeAt: string | null;
  createBy: number;
  updateBy: number;
  createdAt: string;
  updatedAt: string;
  isDelete: number;
  className: string;
  effectivePunchEndAt: string | null;
  subPlans: SubPlan[];
}

const router = useRouter();
const route = useRoute();
const studentId = ref<string | string[]>(route.params.studentId);
const studentInfo = ref<StudentInfo>({} as StudentInfo);

// 班级表格列定义
const classColumns = [
  { title: '班级ID', dataIndex: 'classId', key: 'classId' },
  { title: '班级名称', dataIndex: 'className', key: 'className' },
  { title: '班级年级', dataIndex: 'classGrade', key: 'classGrade' },
  { title: '老师', dataIndex: 'teacherName', key: 'teacherName' },
  { title: '加入时间', dataIndex: 'joinAt', key: 'joinAt' },
  { title: '学习计划', dataIndex: 'studyPlan', key: 'studyPlan' },
  { title: '打卡天数', dataIndex: 'checkinDays', key: 'checkinDays' },
  { title: '最后打卡', dataIndex: 'lastCheckinAt', key: 'lastCheckinAt' },
  { title: '打卡率', dataIndex: 'checkinRate', key: 'checkinRate' },
  { title: '状态', dataIndex: 'status', key: 'status' }
];

// 学习计划表格列定义
const studyPlanColumns = [
  { title: '主任务ID', dataIndex: 'planId', key: 'planId' },
  { title: '主任务名', dataIndex: 'planName', key: 'planName' },
  { title: '子任务1', dataIndex: 'subTask1', key: 'subTask1' },
  { title: '子任务2', dataIndex: 'subTask2', key: 'subTask2' },
  { title: '子任务3', dataIndex: 'subTask3', key: 'subTask3' },
  { title: '子任务4', dataIndex: 'subTask4', key: 'subTask4' },
  { title: '子任务5', dataIndex: 'subTask5', key: 'subTask5' },
  { title: '进度', dataIndex: 'progress', key: 'progress' },
  { title: '发布时间', dataIndex: 'publishAt', key: 'publishAt' },
  { title: '完成时间', dataIndex: 'completeAt', key: 'completeAt' }
];

const planConfigVisible = ref(false);
const currentClassData = ref({});

// 学习计划数据存储
const studyPlansData = ref<MainPlan[]>([]);
// 添加数据加载完成标志
const dataLoaded = ref(false);

// 添加分页设置
const paginationConfig = ref({
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条记录`
});

// 更新表格数据计算方法
const studyPlanTableData = computed(() => {
  const allData = getStudyPlanData();
  // 更新总数
  paginationConfig.value.total = allData.length;
  return allData;
});

// 获取学生详情
const getStudentDetail = async () => {
  try {
    // 处理studentId可能是数组的情况
    const id = Array.isArray(studentId.value) ? studentId.value[0] : studentId.value;
    
    // 自定义函数获取学生详情
    const fetchStudentDetail = async (studentId: string | number) => {
      const userStore = useUserStore();
      const token = userStore.token;
      
      const response = await fetch(`${baseApiUrl}/api/manage/admin/manage/student/${studentId}/detail`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      return result.data;  // 假设API返回格式为 { code: 0, data: {...}, message: '' }
    };
    
    // 获取学生打卡统计数据
    const fetchCheckinStatistics = async (studentId: string | number) => {
      const userStore = useUserStore();
      const token = userStore.token;
      
      const response = await fetch(`${baseApiUrl}/api/manage/admin/manage/student/${studentId}/checkin-statistics`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      console.log('打卡统计原始响应数据:', JSON.stringify(result.data, null, 2));
      return result.data;
    };
    
    // 获取基本信息 - 先获取学生详情
    const data = await fetchStudentDetail(id);
    console.log('学生详情原始响应数据:', JSON.stringify(data, null, 2));
    
    // 获取打卡统计数据
    const checkinStats = await fetchCheckinStatistics(id);
    
    // 将API返回的数据适配到当前组件使用的数据结构
    studentInfo.value = {
      ...studentInfo.value,
      ...data,
      // 兼容旧字段，确保旧代码仍然能够工作
      user_name: data.userName,
      student_id: data.studentId,
      start_at: data.startAt,
      expire_at: data.expireAt,
      student_type: data.studentType,
      
      // 添加打卡统计数据
      totalCheckinDays: checkinStats.total.checkinCount,
      totalCheckinRate: checkinStats.total.checkinRate,
      quarterCheckinDays: checkinStats.quarter.checkinCount,
      quarterCheckinRate: checkinStats.quarter.checkinRate,
      monthCheckinDays: checkinStats.month.checkinCount,
      monthCheckinRate: checkinStats.month.checkinRate,
      weekCheckinDays: checkinStats.week.checkinCount,
      weekCheckinRate: checkinStats.week.checkinRate
    };
    
    // 学生信息加载完成后，再获取学习计划数据
    await fetchStudyPlans();
  } catch (error) {
    console.error('获取学生详情失败', error);
  }
};

// 获取学习计划数据
const fetchStudyPlans = async () => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    
    console.log('开始获取学习计划数据...');
    console.log('当前学生ID:', studentInfo.value.student_id);
    console.log('当前学生班级:', studentInfo.value.classes?.map(c => c.classId) || []);
    
    // 使用fetch调用API替代request函数
    const response = await fetch(`${baseApiUrl}/api/admin/study/plan/main-plan`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const result = await response.json();
    console.log('学习计划原始响应数据类型:', typeof result);
    console.log('学习计划原始响应数据:', JSON.stringify(result, null, 2));
    
    // 确保plansData是数组
    let plansData = [];
    
    // 处理不同的响应格式
    if (Array.isArray(result)) {
      // 如果直接返回数组
      plansData = result;
    } else if (result && typeof result === 'object') {
      // 如果返回对象，查找data字段
      if (Array.isArray(result.data)) {
        plansData = result.data;
      } else if (result.data && typeof result.data === 'object' && result.data.list && Array.isArray(result.data.list)) {
        // 处理可能的分页响应格式 { data: { list: [] } }
        plansData = result.data.list;
      }
    }
    
    console.log('处理后的计划数据数组长度:', plansData.length);
    
    // 等待studentInfo加载完成
    if (!studentInfo.value || !studentInfo.value.student_id) {
      console.log('学生信息尚未加载完成，无法过滤学习计划');
      studyPlansData.value = [];
      dataLoaded.value = true;  // 标记为已加载
      return;
    }
    
    // 如果获取到的计划为空，直接返回
    if (plansData.length === 0) {
      console.log('获取到的计划数据为空');
      studyPlansData.value = [];
      dataLoaded.value = true;  // 标记为已加载
      return;
    }
    
    // 过滤出当前学生的学习计划
    const studentPlans = plansData.filter(plan => {
      // 确保plan是有效对象
      if (!plan || typeof plan !== 'object') {
        console.log('无效的计划数据:', plan);
        return false;
      }
      
      // 检查是否是学生个人计划（classId以STU开头并包含学生ID）
      const isPersonalPlan = plan.classId && 
                           typeof plan.classId === 'string' && 
                           plan.classId.startsWith('STU') && 
                           plan.classId.includes(studentInfo.value.student_id);
      
      // 检查是否是学生所在班级的计划
      const isClassPlan = studentInfo.value.classes && 
                        Array.isArray(studentInfo.value.classes) && 
                        studentInfo.value.classes.some(cls => cls.classId === plan.classId);
      
      console.log('计划ID:', plan.planId, '班级ID:', plan.classId, '是个人计划:', isPersonalPlan, '是班级计划:', isClassPlan);
      
      // 重要修改：获取所有计划，不论是个人计划还是班级计划
      // 这里不做过滤，返回所有有效的计划数据
      return true;
    });
    
    console.log('过滤后的学生计划数量:', studentPlans.length);
    console.log('过滤后的学生计划数据:', JSON.stringify(studentPlans, null, 2));
    
    // 设置计划数据
    studyPlansData.value = studentPlans;
    
    // 标记数据已加载完成，触发重新渲染
    dataLoaded.value = true;
    
    console.log('学习计划数据设置完成，数据长度:', studyPlansData.value.length);
  } catch (error) {
    console.error('获取学习计划失败', error);
    message.error('获取学习计划失败');
    studyPlansData.value = [];
    // 即使出错也标记为已加载完成，以便显示错误状态
    dataLoaded.value = true;
  }
};

// 获取展开的学习计划数据
const getStudyPlanData = () => {
  console.log('调用getStudyPlanData, studyPlansData长度:', studyPlansData.value.length);
  
  // 使用从API获取的学习计划数据
  if (studyPlansData.value.length > 0) {
    const result = studyPlansData.value.map((plan, index) => {
      const planData: any = {
        id: index,
        planId: plan.planId,
        planName: plan.planName,
        progress: plan.progress || 0,
        publishAt: plan.publishAt,
        completeAt: plan.completeAt || plan.effectivePunchEndAt
      };
      
      // 处理子任务
      if (plan.subPlans && plan.subPlans.length > 0) {
        // 最多展示5个子任务
        for (let i = 0; i < Math.min(plan.subPlans.length, 5); i++) {
          planData[`subTask${i+1}`] = plan.subPlans[i].subPlanName;
        }
      }
      
      return planData;
    });
    
    console.log('API数据处理后返回结果:', JSON.stringify(result, null, 2));
    return result;
  }
  
  // 如果API数据为空，回退到旧的逻辑
  if (!studentInfo.value.classes || studentInfo.value.classes.length === 0) {
    console.log('无班级数据，返回空数组');
    return [];
  }
  
  const studyPlanData: any[] = [];
  let idCounter = 0;
  
  studentInfo.value.classes.forEach(cls => {
    if (cls.mainPlans && cls.mainPlans.length > 0) {
      // 处理每个主任务
      cls.mainPlans.forEach(mainPlan => {
        const planData: any = {
          id: idCounter++,
          planId: mainPlan.planId,
          planName: mainPlan.planName,
          progress: mainPlan.progress || 0,
          publishAt: mainPlan.publishAt,
          completeAt: mainPlan.completeAt || mainPlan.effectivePunchEndAt
        };
        
        // 处理子任务
        if (mainPlan.subPlans && mainPlan.subPlans.length > 0) {
          // 最多展示5个子任务
          for (let i = 0; i < Math.min(mainPlan.subPlans.length, 5); i++) {
            planData[`subTask${i+1}`] = mainPlan.subPlans[i].subPlanName;
          }
        }
        
        studyPlanData.push(planData);
      });
    } else if (cls.studyPlan) {
      // 兼容旧数据结构，确保即使没有新格式数据也能显示
      const planData: any = {
        id: idCounter++,
        planId: cls.classId || '-',
        planName: Array.isArray(cls.studyPlan) ? cls.studyPlan[0] : cls.studyPlan,
        progress: parseCheckinRate(cls.checkinRate),
        publishAt: cls.startAt,
        completeAt: cls.expireAt
      };
      
      studyPlanData.push(planData);
    }
  });
  
  console.log('旧数据处理后返回结果:', JSON.stringify(studyPlanData, null, 2));
  return studyPlanData;
};

// 格式化日期
const formatDate = (dateString: string | string[] | undefined | null) => {
  if (!dateString) return '-';
  
  // 如果是数组，取第一个元素
  const dateValue = Array.isArray(dateString) ? dateString[0] : dateString;
  
  // 格式化日期
  return new Date(dateValue).toLocaleDateString();
};

// 获取学生类型
const getStudentType = () => {
  if (!studentInfo.value.student_type) return '-';
  return studentInfo.value.student_type === 1 ? '线上' : '线下';
};

// 获取学生状态
const getStudentStatus = () => {
  if (studentInfo.value.status === undefined) return '-';
  
  const statusMap: Record<number, string> = {
    0: '停用',
    1: '学习中',
    2: '待续费',
    4: '已毕业'
  };
  
  return statusMap[studentInfo.value.status] || '未知';
};

// 获取班级信息显示
const getClassInfo = () => {
  if (!studentInfo.value.classes || studentInfo.value.classes.length === 0) {
    return '未分班';
  }
  
  const classNames = studentInfo.value.classes.map(cls => cls.className).join('、');
  return classNames;
};

// 解析打卡率百分比
const parseCheckinRate = (rate: string): number => {
  if (!rate) return 0;
  // 去掉百分比符号并转为数字
  return parseFloat(rate.replace('%', ''));
};

// 获取监护人关系
const getGuarderRelation = () => {
  if (studentInfo.value.guarderRelation === undefined) return '-';
  
  const relationMap: Record<number, string> = {
    1: '父亲',
    2: '母亲',
    3: '其他'
  };
  
  return relationMap[studentInfo.value.guarderRelation] || '未知';
};

// 获取年级
const getGrade = () => {
  // 首先显示学生自身的年级
  let studentGrade = '';
  if (studentInfo.value.grade !== undefined) {
    const gradeMap: Record<number, string> = {
      0: '幼儿园',
      1: '小学一年级',
      2: '小学二年级',
      3: '小学三年级',
      4: '小学四年级',
      5: '小学五年级',
      6: '小学六年级',
      7: '初中一年级',
      8: '初中二年级',
      9: '初中三年级'
    };
    
    studentGrade = gradeMap[studentInfo.value.grade] || '未知';
  }
  
  // 然后检查班级信息中的年级
  if (studentInfo.value.classes && studentInfo.value.classes.length > 0) {
    // 收集所有不同的班级年级
    const classGrades: string[] = [];
    
    studentInfo.value.classes.forEach(cls => {
      if (cls.classGrade !== undefined) {
        const gradeMap: Record<number, string> = {
          0: '幼儿园',
          1: '小学一年级',
          2: '小学二年级',
          3: '小学三年级',
          4: '小学四年级',
          5: '小学五年级',
          6: '小学六年级',
          7: '初中一年级',
          8: '初中二年级',
          9: '初中三年级'
        };
        
        const gradeText = gradeMap[cls.classGrade] || `未知(${cls.classGrade})`;
        if (!classGrades.includes(gradeText)) {
          classGrades.push(gradeText);
        }
      }
    });
    
    if (classGrades.length > 0) {
      return classGrades.join('、');
    }
  }
  
  // 如果没有班级年级信息，则返回学生本身的年级或默认值
  return studentGrade || '-';
};

// 获取带班老师信息
const getTeacherInfo = () => {
  if (!studentInfo.value.classes || studentInfo.value.classes.length === 0) {
    return '-';
  }
  
  // 收集所有不同的老师名称
  const teacherNames: string[] = [];
  
  studentInfo.value.classes.forEach(cls => {
    if (cls.teacherName && !teacherNames.includes(cls.teacherName)) {
      teacherNames.push(cls.teacherName);
    }
  });
  
  if (teacherNames.length > 0) {
    return teacherNames.join('、');
  }
  
  return '-';
};

// 计算账号剩余天数
const getRemainingDays = () => {
  if (!studentInfo.value.expire_at) return 0;
  
  const today = new Date();
  const expireDate = new Date(studentInfo.value.expire_at);
  
  // 计算剩余天数（向上取整）
  const remainingDays = Math.ceil((expireDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
  
  // 如果已过期，返回0，否则返回剩余天数
  return remainingDays > 0 ? remainingDays : 0;
};

// 计算年龄
const calculateAge = (birthdayStr: string | undefined | null) => {
  if (!birthdayStr) return '-';
  
  const birthDate = new Date(birthdayStr);
  const today = new Date();
  
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  
  // 如果当前月份小于出生月份，或者月份相同但当前日期小于出生日期，则年龄减1
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  
  return age;
};

// 计算已学习时长（从开始时间到现在，或到结束时间如果已过期）
const getStudyDuration = () => {
  if (!studentInfo.value.start_at) return 0;
  
  const startDate = new Date(studentInfo.value.start_at);
  const today = new Date();
  
  // 如果已过期，计算到过期日为止，否则计算到今天
  let endDate = today;
  if (studentInfo.value.expire_at) {
    const expireDate = new Date(studentInfo.value.expire_at);
    if (expireDate < today) {
      endDate = expireDate;
    }
  }
  
  // 计算学习天数（向下取整）
  const studyDays = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
  
  return studyDays > 0 ? studyDays : 0;
};

// 获取城市区域
const getCityRegion = () => {
  let region = '';
  
  // 拼接省市信息（如果有）
  if (studentInfo.value.province) {
    region += studentInfo.value.province;
  }
  
  if (studentInfo.value.city) {
    if (region) region += ' - ';
    region += studentInfo.value.city;
  }
  
  return region || '-';
};

// 获取班级名称
const getClassNames = () => {
  if (!studentInfo.value.classes || studentInfo.value.classes.length === 0) {
    return '未分班';
  }
  
  const classNames = studentInfo.value.classes.map(cls => cls.className).join('、');
  return classNames;
};

// 获取老师名称
const getTeacherNames = () => {
  if (!studentInfo.value.classes || studentInfo.value.classes.length === 0) {
    return '-';
  }
  
  // 收集所有不同的老师名称
  const teacherNames: string[] = [];
  
  studentInfo.value.classes.forEach(cls => {
    if (cls.teacherName && !teacherNames.includes(cls.teacherName)) {
      teacherNames.push(cls.teacherName);
    }
  });
  
  if (teacherNames.length > 0) {
    return teacherNames.join('、');
  }
  
  return '-';
};

// 获取打卡率颜色类
const getRateColorClass = (rate: string | undefined): string => {
  if (!rate) return '';
  const numericRate = parseFloat(rate.replace('%', ''));
  if (numericRate >= 80) return 'rate-high';
  if (numericRate >= 50) return 'rate-medium';
  return 'rate-low';
};

// 打开计划配置弹窗
const setPlan = (record) => {
  console.log('正在配置计划的学生ID:', record.id);
  // 构造classData数据结构，确保与班级管理页中的格式一致
  currentClassData.value = {
    classId: record.classes && record.classes.length > 0 ? record.classes[0].classId : '',
    studyPlan: []
  };
  planConfigVisible.value = true;
};

// 处理计划确认
const handlePlanConfirm = async (data) => {
  try {
    console.log('计划配置数据:', data);
    // 获取传入的数据
    const { studyPlan } = data;
    
    // 如果没有有效计划项，弹出提示
    if (!studyPlan || studyPlan.length === 0) {
      message.warning('请至少添加一个有效的计划项');
      return;
    }
    
    // 根据API要求构造请求参数
    const plans = studyPlan.map(plan => {
      // 构造计划项基本信息
      const planItem: any = {
        planName: plan.mainPlanName,            // 主计划名称
        subPlans: plan.subPlanName,             // 子计划名称作为单个子计划
        mark: ''                                // 计划备注，默认为空
      };
      
      // 如果提供了打卡开始时间，则添加到计划项中
      if (plan.startTime) {
        planItem.punchStartAt = plan.startTime;
      }
      
      return planItem;
    });
    
    // 构建符合API规范的请求参数
    const requestParams = {
      studentId: parseInt(studentInfo.value.id),  // 学生ID
      plans: plans
    };
    
    // 构建请求URL - 使用新的API端点
    const requestUrl = '/api/admin/study/plan/main-plan/student-create';
    
    // 打印请求信息
    console.log('==================================================');
    console.log('请求URL:', requestUrl);
    console.log('请求参数:', JSON.stringify(requestParams, null, 2));
    console.log('==================================================');
    
    // 使用fetch函数替代request函数调用API
    const userStore = useUserStore();
    const token = userStore.token;
    
    const response = await fetch(`${baseApiUrl}${requestUrl}`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestParams)
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const result = await response.json();
    console.log('保存计划配置成功，返回结果:', result);
    message.success('计划配置保存成功');
    getStudentDetail(); // 重新加载学生详情数据
    planConfigVisible.value = false; // 关闭弹窗
  } catch (error) {
    console.error('保存计划配置失败', error);
    message.error('保存计划配置失败，请重试');
  }
};

onMounted(() => {
  getStudentDetail();
});
</script>

<style scoped>
.header-title {
  font-size: 18px;
  font-weight: bold;
}

.info-card {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
}

.info-item {
  margin-bottom: 8px;
}

.label {
  color: #999;
  font-size: 14px;
}

.value {
  font-size: 16px;
  font-weight: 500;
}

.stat-card {
  text-align: left;
  border-radius: 4px;
  padding: 16px;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin: 8px 0;
  line-height: 1.2;
}

.stat-unit {
  font-size: 14px;
  color: #999;
  margin-left: 4px;
}

.stat-rate {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.rate-value {
  font-weight: bold;
  font-size: 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-actions {
  display: flex;
  gap: 8px;
}

h3 {
  margin: 0;
}

.rate-high {
  color: #52c41a;
}

.rate-medium {
  color: #faad14;
}

.rate-low {
  color: #f5222d;
}
</style>